/*
 * $Id$
 *
 * Copyright ( c ) 2014 XuNuo Corporation. All Rights Reserved.
 *
 * This software is the confidential and proprietary information of XuNuo
 * Corporation ("Confidential Information").  You shall not disclose such
 * Confidential Information and shall use it only in accordance with the terms
 * of the license agreement you entered into with XuNuo Corporation or a XuNuo
 * authorized reseller (the "License Agreement"). XuNuo may make changes to the
 * Confidential Information from time to time. Such Confidential Information may
 * contain errors.
 *
 * EXCEPT AS EXPLICITLY SET FORTH IN THE LICENSE AGREEMENT, XuNuo DISCLAIMS ALL
 * WARRANTIES, COVENANTS, REPRESENTATIONS, INDEMNITIES, AND GUARANTEES WITH
 * RESPECT TO SOFTWARE AND DOCUMENTATION, WHETHER EXPRESS OR IMPLIED, WRITTEN OR
 * ORAL, STATUTORY OR OTHERWISE INCLUDING, WITHOUT LIMITATION, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY, TITLE, NON-INFRINGEMENT AND FITNESS FOR A
 * PARTICULAR PURPOSE. XuNuo DOES NOT WARRANT THAT END USER'S USE OF THE
 * SOFTWARE WILL BE UNINTERRUPTED, ERROR FREE OR SECURE.
 *
 * XuNuo SHALL NOT BE LIABLE TO END USER, OR ANY OTHER PERSON, CORPORATION OR
 * ENTITY FOR INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL
 * DAMAGES, OR DAMAGES FOR LOSS OF PROFITS, REVENUE, DATA OR USE, WHETHER IN AN
 * ACTION IN CONTRACT, TORT OR OTHERWISE, EVEN IF XuNuo HAS BEEN ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGES. XuNuo' TOTAL LIABILITY TO END USER SHALL NOT
 * EXCEED THE AMOUNTS PAID FOR THE XuNuo SOFTWARE BY END USER DURING THE PRIOR
 * TWELVE (12) MONTHS FROM THE DATE IN WHICH THE CLAIM AROSE.  BECAUSE SOME
 * STATES OR JURISDICTIONS DO NOT ALLOW LIMITATION OR EXCLUSION OF CONSEQUENTIAL
 * OR INCIDENTAL DAMAGES, THE ABOVE LIMITATION MAY NOT APPLY TO END USER.
 *
 * Copyright version 2.0
 */
package com.th.supcom.pds.phamapply.client.widget.inpharmacyreturn;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.carefx.framework.container.client.context.AppContext;

import com.extjs.gxt.ui.client.event.Listener;
import com.extjs.gxt.ui.client.event.MessageBoxEvent;
import com.extjs.gxt.ui.client.widget.Component;
import com.extjs.gxt.ui.client.widget.Dialog;
import com.extjs.gxt.ui.client.widget.Info;
import com.extjs.gxt.ui.client.widget.button.Button;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.th.supcom.framework.web.gwt.client.widget.FcMessageBox;
import com.th.supcom.pds.common.client.model.CodeConstants;
import com.th.supcom.pds.common.enums.BatchNumberManagerFlag;
import com.th.supcom.pds.common.utils.ClientUtils;
import com.th.supcom.pds.phamapply.client.common.InpPhamApplyServiceFactory;
import com.th.supcom.pds.phamapply.client.model.InPharmacyReturnResult;
import com.th.supcom.pds.phamapply.client.model.InpPhamApplyDetailModel;
import com.th.supcom.pds.phamapply.client.service.InPharmacyReturnRpcAsync;

/**
 * 门诊退药Action
 * 
 * @author yzhang
 */
public class InPharmacyReturnAction
{
    private InPharmacyReturnFields m_inPharmacyReturnFields;
    private InPharmacyReturnGridPanel m_inPharmacyReturnGridPanel;
    private InPharmacyReturnMasterGridPanel m_inPharmacyReturnMasterGridPanel;
    private List <List <InpPhamApplyDetailModel>> m_inpPhamApplyDetailModelList;
    private InPharmacyReturnMainPanel m_mainPanel;

    private final static InPharmacyReturnRpcAsync S_PRPCASYNC = InpPhamApplyServiceFactory.getInPharmacyReturnService ();

    /**
     * 构造函数
     */
    public InPharmacyReturnAction ()
    {

    }

    /**
     * 通过电子退药单、患者ID查询退药明细信息
     * 
     * @param successComponent
     * @param failComponent
     */
    public void findInpPhamApplyDetailByApplyNo (final Component successComponent, final Component failComponent)
    {
        if (m_inPharmacyReturnFields.getPrescNoField ().getValue () == null
            && m_inPharmacyReturnFields.getPatiIdField ().getValue () == null)
        {
            ClientUtils.alertMessageBox ("输入不能为空！请重新输入", failComponent);
            return;
        }
        clear (false);
        String applyNo = m_inPharmacyReturnFields.getPrescNoField ().getValue ();
        String performedBy = ClientUtils.getOrgModel ().getOrgCode ();
        String patientId = m_inPharmacyReturnFields.getPatiIdField ().getValue ();
        mask ();
        S_PRPCASYNC.getInpPhamApplyDetailByApplyNo (applyNo, patientId, performedBy,
                                                    new AsyncCallback <InPharmacyReturnResult> ()
                                                    {

                                                        @Override
                                                        public void onSuccess (InPharmacyReturnResult result)
                                                        {
                                                            unmask ();
                                                            m_inpPhamApplyDetailModelList = result.getInpPhamApplyDetailModelsList ();
                                                            m_inPharmacyReturnMasterGridPanel.refresh (result.getInpPhamApplyDetailModels ());
                                                            m_inPharmacyReturnMasterGridPanel.getCheckmodel ()
                                                                                             .select (0, true);
                                                            successComponent.focus ();

                                                        }

                                                        @Override
                                                        public void onFailure (Throwable caught)
                                                        {
                                                            unmask ();
                                                            ClientUtils.alertMessageBox (caught.getMessage (),
                                                                                         failComponent);

                                                        }
                                                    });

    }

    /**
     * 当点击主记录表格处方时 请领明细表格相应弹出或隐藏内容
     * 
     * @param selectedModel
     */
    public void doSelectedChange (List <InpPhamApplyDetailModel> selectedModel)
    {
        if (selectedModel == null || selectedModel.isEmpty ())
        {
            m_inPharmacyReturnGridPanel.getGrid ().getStore ().removeAll ();
        }
        if (m_inpPhamApplyDetailModelList == null || m_inpPhamApplyDetailModelList.isEmpty ())
        {
            return;
        }
        final List <InpPhamApplyDetailModel> applyDetails = getDetailSelected (selectedModel,
                                                                               m_inpPhamApplyDetailModelList);
        m_inPharmacyReturnGridPanel.getGrid ().getStore ().removeAll ();
        m_inPharmacyReturnGridPanel.getGrid ().getStore ().add (applyDetails);
    }

    /**
     * 获得选中主记录对应的所有明细记录
     * 
     * @return
     */
    private List <InpPhamApplyDetailModel> getDetailSelected (final List <InpPhamApplyDetailModel> models,
                                                              final List <List <InpPhamApplyDetailModel>> modelList)
    {
        final List <InpPhamApplyDetailModel> modelSelected = new ArrayList <InpPhamApplyDetailModel> ();
        // 获取勾选明细记录
        for (final InpPhamApplyDetailModel detalModel : models)
        {
            for (final List <InpPhamApplyDetailModel> detailModelList : modelList)
            {
                if (detalModel.getApplyNo ().equals (detailModelList.get (0).getApplyNo ()))
                {
                    modelSelected.addAll (detailModelList);
                }
            }
        }
        return modelSelected;
    }

    /**
     * 住院药房退药action
     * 
     * @param successComponent
     * @param failComponent
     */
    public void drugReturn (final Component successComponent, final Component failComponent)
    {
        List <InpPhamApplyDetailModel> applyDetailModels = (List <InpPhamApplyDetailModel>) m_inPharmacyReturnGridPanel.getModels ();
        if (applyDetailModels.isEmpty ())
        {
            ClientUtils.alertMessageBox ("请先查询到相关信息再进行此操作！", failComponent);
            return;
        }
        for (InpPhamApplyDetailModel model : applyDetailModels)
        {
            if ((model.getPhamBatchNo () == null || model.getExpiryDate () == null)
                && BatchNumberManagerFlag.OnBatchManager.getEnumCode ().equals (model.getBatchNumberManagerFlag ()))
            {
                ClientUtils.alertMessageBox ("请先输入批次号和有效期再进行此操作。", failComponent);
                return;
            }
        }
        FcMessageBox.confirm ("提示", "确定进行退药操作?", new Listener <MessageBoxEvent> ()
        {
            @Override
            public void handleEvent (MessageBoxEvent be)
            {
                doWithdramDrugAction (successComponent, failComponent, be);
            }
        }, Dialog.YES);
    }

    /**
     * 退药操作动作
     * 
     * @param successComponent
     * @param failComponent
     * @param be
     */
    private void doWithdramDrugAction (final Component successComponent, final Component failComponent,
                                       MessageBoxEvent be)
    {
        Button btn = be.getButtonClicked ();
        if (btn.getText ().equals ("否"))
        {
            failComponent.focus ();
            return;
        }
        String operator = ClientUtils.geteEmpModel ().getEmpCode ();
        String performedBy = ClientUtils.getOrgModel ().getOrgCode ();
        String nurseUnit = m_inPharmacyReturnMasterGridPanel.getModels ().get (0).getNurseUnit ();
        Map <String, Object> infoMap = new HashMap <String, Object> ();
        infoMap.put ("operator", operator);
        infoMap.put ("nurseUnit", nurseUnit);
        List <InpPhamApplyDetailModel> models = m_inPharmacyReturnGridPanel.getModels ();
        for (InpPhamApplyDetailModel model : models)
        {
            model.setExecDispensary (performedBy);
        }
        S_PRPCASYNC.modifyInPhacyReturn (models, infoMap, new AsyncCallback <Void> ()
        {

            @Override
            public void onSuccess (Void result)
            {
             	m_mainPanel.unmask ();
                Info.display (CodeConstants.PROMPT, "退药成功");
                clear (true);
                successComponent.focus ();
            }

            @Override
            public void onFailure (Throwable caught)
            {
             	m_mainPanel.unmask ();
                ClientUtils.alertMessageBox (caught.getMessage (), successComponent);
                clear (false);
            }
        });
    }

    /**
     * 清除
     * 
     * @param isClearAll true 清空所有 false 不清空输入框
     */
    public void clear (boolean isClearAll)
    {
        if (isClearAll)
        {
            m_inPharmacyReturnFields.getPrescNoField ().clear ();
            m_inPharmacyReturnFields.getPatiIdField ().clear ();
        }
        m_inPharmacyReturnGridPanel.getStore ().removeAll ();
        m_inPharmacyReturnMasterGridPanel.getStore ().removeAll ();
    }

    private void mask ()
    {
        m_mainPanel.mask ("加载中...");
    }

    private void unmask ()
    {
        m_mainPanel.unmask ();
    }

    public void setInPharmacyReturnMasterGridPanel (InPharmacyReturnMasterGridPanel inPharmacyReturnMasterGridPanel)
    {
        m_inPharmacyReturnMasterGridPanel = inPharmacyReturnMasterGridPanel;
    }

    public void setInPharmacyReturnFields (InPharmacyReturnFields inPharmacyReturnFields)
    {
        m_inPharmacyReturnFields = inPharmacyReturnFields;
    }

    public void setInPharmacyReturnGridPanel (InPharmacyReturnGridPanel inPharmacyReturnGridPanel)
    {
        m_inPharmacyReturnGridPanel = inPharmacyReturnGridPanel;
    }

    public void setMainPanel (InPharmacyReturnMainPanel mainPanel)
    {
        m_mainPanel = mainPanel;
    }

    /** 提交路径. */
    public static final String SCC_BRANCH = "$URL$";

    /** 提交日期. */
    public static final String SCC_LAST_MODIFICATION_DATE = "$Date$";

    /** 最终修改人员. */
    public static final String SCC_LAST_MODIFIER_NAME = "$Author$";

    /** 最终版本号. */
    public static final String SCC_REVISION = "$Revision$";
}
